#pragma once

#include "mission.h"
#include "mission_manager.h"
#include "mission_event.h"
#include "userAPI.h"

using namespace AI9;

class basic_manage_mission: public mission
{
public:
	basic_manage_mission(mission *parent_mission, gtype_list &troop, Position target, int upper_bound = 300) : mission(parent_mission, troop) 
	{
		m_hp_limit = upper_bound;
		m_target = target;
	}

	virtual void execute()
	{
		LOG << this->get_type() << " executing"  << endl;
		UserAPI &api = mission_manager::get_intance()->get_api();

		mission_manager::get_intance()->set_general_mission(m_troop.front(), this);
		if (mission_manager::get_intance()->actioned_state() == false && mission_manager::get_intance()->active_general() == m_troop.front())
			event_arrived(new basic_mission_event(this));
	}

	virtual void event_arrived(mission_event *e)
	{
		LOG << this->get_type() << " event_arrived"  << endl;
		UserAPI &api = mission_manager::get_intance()->get_api();

		if (e->get_type() == "basic_mission_event")
		{
			mission_manager::get_intance()->set_actioned_state(true);

			Position start = api.GetCntArmy()->pos;
			if (!(start == m_target))
				api.Move(mission_manager::get_intance()->get_action_queue(), start, m_target);				

			LandCity* city = api.GetCity(m_target);
			if (city != NULL) {
				mission_manager::get_intance()->set_actioned_state(true);
				if (city->HP < m_hp_limit) api.RepairCity(mission_manager::get_intance()->get_action_queue());
				else if (!city->hasBarrack) api.BuildBarrack(mission_manager::get_intance()->get_action_queue());

				if (city->hasBarrack)
					api.Recruit(mission_manager::get_intance()->get_action_queue());

			} else {
				LOG << "no city lies at target" << endl;
				abort();
			}

			return;
		}

		LOG << "unhandled event " << e->get_type();
		abort();
	}

	virtual void cancel()
	{
		//	 do nothing
	}

	virtual std::string get_type() { return "basic_manage_mission"; };

	int m_hp_limit;
	Position m_target;
};